package database;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

abstract class DatabaseTableTemplate extends SQLiteOpenHelper {
	protected SQLiteDatabase connector;
	protected Cursor cursor;
	protected Context context;
	private static final int DATABASE_VERSION = 6;
	
	public DatabaseTableTemplate(Context context) {
		super(context, DatabaseFacade.DATABASE_NAME, null, DATABASE_VERSION);
		this.context = context;
	}
	
	@Override
	public final void onCreate(SQLiteDatabase database) {
		database.execSQL(ListDatabaseConnector.DATABASE);
		database.execSQL(UserDatabaseConnector.DATABASE);
	}

	@Override
	public final void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + UserDatabaseConnector.TABLE_NAME); //$NON-NLS-1$
		db.execSQL("DROP TABLE IF EXISTS " + ListDatabaseConnector.TABLE_NAME); //$NON-NLS-1$
		onCreate(db);
	}
	

	protected void doOpen(){
		if(this.connector == null)
			this.connector = getWritableDatabase();	
	}
	
	protected void doClose(){
		if(this.cursor != null){
			this.cursor.close();
			this.cursor = null;
		}
		if(this.connector != null){
			this.connector.close();
			this.connector = null;
		}
	}

	protected abstract String getTableStructure();
	
	public static void addToListAlphabetacally(List<String> list, String add, boolean unique){
		if(!unique || !list.contains(add)){
			int i = Collections.binarySearch(list, add, new Comparator<String>(){
				@Override
				public int compare(String lhs, String rhs) {
					return lhs.compareToIgnoreCase(rhs);
				}});
			if(i < 0){
				list.add(-(i + 1), add);
			} else {
				list.add(i, add);
			}
		}
	}
}